package com.njupt.towersystem.services.impl;

import com.njupt.towersystem.domain.managerinfos;
import com.njupt.towersystem.mapper.ManagerInfoMapper;
import com.njupt.towersystem.services.ManagerService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.UUID;

@Service
public class ManagerServicesImpl implements ManagerService {
//   @Resource
//   private ManagerInfoMapper managerInfoMapper;
   @Resource
   private StringRedisTemplate stringRedisTemplate;

    @Override
    public managerinfos login(String loginname, String loginpwd, String token) {
        managerinfos mi=managerinfos.builder()
                .loginname(loginname)
                .loginpwd(loginpwd).build();
        if (loginname!=null){
            Object res = stringRedisTemplate
                    .opsForHash().get("manages", loginname+loginpwd);
            if (res!=null){
//                生成唯一令牌
                String token01 = UUID.randomUUID().toString().replaceAll("-", "");
//              将令牌存放到redis数据库中 让令牌保存30分钟
                stringRedisTemplate.opsForValue()
                        .set(token01,loginname+loginpwd, Duration.ofMinutes(30+(int)(Math.random()*100)));

//                找到对应用户
                String[] infos = res.toString().split(",");
                managerinfos mis = managerinfos.builder()
                        .userid(Integer.parseInt(infos[0]))
                        .username(infos[1])
                        .loginname(infos[2])
                        .loginpwd(infos[3])
                        .tel(infos[4])
                        .department(infos[5])
                        .token(token01)
                        .build();
                return mis;
            }else {
//                找不到用户
                return null;
            }

        }else{
//            验证用户输入的令牌是否存在
            String res = stringRedisTemplate.opsForValue()
                    .get(token);
            if (res!=null){
//                令牌存在 按照令牌的key取loginname和loginpwd
                Object obj = stringRedisTemplate
                        .opsForHash().get("manages", res);
                String[] infos = res.toString().split(",");
                managerinfos mis = managerinfos.builder()
                        .userid(Integer.parseInt(infos[0]))
                        .username(infos[1])
                        .loginname(infos[2])
                        .loginpwd(infos[3])
                        .tel(infos[4])
                        .department(infos[5])
                        .token(token)
                        .build();
                return mis;
            }
            return null;

        }

    }
}
